<template>
  <van-action-sheet v-model="show" title="频道管理" @closed="isEdit = false">
    <div class="content">
      <div class="top">
        <span class="title">我的频道</span>
        <van-button
          plain
          type="danger"
          size="small"
          @click="isEdit = !isEdit"
          >{{ isEdit ? '取消' : '编辑' }}</van-button
        >
      </div>
      <van-grid>
        <van-grid-item v-for="(item, index) in list" :key="item.id">
          <div
            @click="itemClick(index)"
            :class="{ active: currIndex === index }"
          >
            {{ item.name }}
          </div>
          <van-icon
            v-if="isEdit && item.name !== '推荐'"
            name="cross"
            class="icon"
            @click="iconClick(index)"
          />
        </van-grid-item>
      </van-grid>
      <div class="bottom">
        <span class="title">可选频道</span>
      </div>
      <van-grid>
        <!-- allList-list -->
        <van-grid-item
          v-for="item in newList"
          :key="item.id"
          :text="item.name"
          @click="$emit('addList', item)"
        ></van-grid-item>
      </van-grid>
    </div>
  </van-action-sheet>
</template>
<script>
import { channels } from '@/api/home'
export default {
  props: {
    list: {
      type: Array,
      required: true
    },
    currIndex: {
      type: Number,
      required: true
    }
  },
  //   使用场景：依赖一个或者多个值产生一个新的值
  computed: {
    newList () {
      // 计算产生allList-list数据
      return this.allList.filter(item => {
        // return item这一项是否在list中存在，存在，reutrn false 不存在,return true
        // return item的id是否在list中每一项中是否存在
        // 查找 list中是否存在item.id
        // 返回值=数据.find(item=>{return boolean,true,返回值=item 所有项都是false,返回值undefined })
        const findItem = this.list.find(item2 => item.id === item2.id)
        return !findItem
      })
    }
  },
  data () {
    return {
      show: false,
      allList: [],
      isEdit: false
    }
  },
  created () {
    this.getData()
  },
  methods: {
    async getData () {
      const res = await channels()
      this.allList = res.data.data.channels
      // console.log('所有频道数据', res)
    },
    // 删除我的频道
    iconClick (index) {
      this.$emit('delList', index)
      if (this.currIndex > index && this.currIndex > 0) {
        this.$emit('setCurrIndex', this.currIndex - 1)
      }
    },

    // 我的频道点击事件
    itemClick (index) {
      // 修改下标
      this.$emit('setCurrIndex', index)
      //   关闭弹框
      this.show = false
    }
  }
}
</script>
<style lang="less" scoped>
.content {
  padding: 15px;
  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    ::v-deep .van-button__text {
      color: red;
    }
  }
  .active {
    color: red;
  }
  .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
